﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using FileExplorer_TreeView;
using Mp3TagReader.com.wikia.lyrics;
using TagLib;

namespace Mp3TagReader
{
    public partial class MainForm : Form
    {
        private FileExplorer fe = new FileExplorer();
        private static string filePath = @"E:\Untagged Music";
        private static string selectedFileName = string.Empty;
        private static string temp = string.Empty;
        private static int selectedRowIndex = 0;
        private static int flag = 0;
        private static List<string> ls = new List<string>();
        private MySortableBindingList<Mp3Info> listMp3Infos = new MySortableBindingList<Mp3Info>();
        private FileInfo[] mp3Files = null;
        private FileInfo[] wmaFiles = null;
        private FileInfo[] flacFiles = null;

        private FileInfo[] mp3Files_Untagged = null;
        private FileInfo[] wmaFiles_Untagged = null;
        private FileInfo[] flacFiles_Untagged = null;

        private FileInfo[] mp4Files = null;
        private FileInfo[] mpgFiles = null;
        private FileInfo[] wmvFiles = null;
        private FileInfo[] flvFiles = null;
        private FileInfo[] aviFiles = null;

        private WMPLib.IWMPPlaylist pl;
        private WMPLib.IWMPPlaylistArray plItems;
        private WMPLib.WindowsMediaPlayer windowsMediaPlayer = new WMPLib.WindowsMediaPlayer();

        [System.Runtime.InteropServices.DllImport("winmm.dll")]
        private static extern long mciSendString(string strCommand, StringBuilder strReturn, int iReturnLength, IntPtr hwndCallback);

        public MainForm()
        {
            InitializeComponent();

            fe.CreateTree(this.treeViewFolder);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                gridView.AutoGenerateColumns = false;
                DataGridViewTextBoxColumn columnFilePath = new DataGridViewTextBoxColumn();
                columnFilePath.DataPropertyName = "Path";
                columnFilePath.Name = "ColumnPath";
                columnFilePath.Visible = false;
                DataGridViewTextBoxColumn columnFileName = new DataGridViewTextBoxColumn();
                columnFileName.DataPropertyName = "Name";
                columnFileName.HeaderText = "File Name";
                columnFileName.Width = gridView.Width - 180;
                DataGridViewTextBoxColumn columnFileDate = new DataGridViewTextBoxColumn();
                columnFileDate.DataPropertyName = "CreationTime";
                columnFileDate.HeaderText = "Creation Time";
                columnFileDate.Width = 130;

                gridView.Columns.Add(columnFilePath);
                gridView.Columns.Add(columnFileName);
                gridView.Columns.Add(columnFileDate);

                txtFilePath.Text = filePath;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ClearMp3List()
        {
            try
            {
                gridView.DataSource = null;
                listMp3Infos.Clear();
            }
            catch (Exception) { }
        }

        private void ListFiles()
        {
            string _temp = string.Empty;
            try
            {
                ClearMp3List();
                _temp = filePath;
                filePath = txtFilePath.Text;
                DirectoryInfo di = new DirectoryInfo(filePath);
                mp3Files = di.GetFiles("*.mp3", SearchOption.AllDirectories);
                wmaFiles = di.GetFiles("*.wma", SearchOption.AllDirectories);
                flacFiles = di.GetFiles("*.flac", SearchOption.AllDirectories);
                foreach (FileInfo fi in mp3Files)
                {
                    listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                }
                foreach (FileInfo fi in wmaFiles)
                {
                    listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                }
                foreach (FileInfo fi in flacFiles)
                {
                    listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                }

                mp4Files = di.GetFiles("*.mp4", SearchOption.AllDirectories);
                aviFiles = di.GetFiles("*.avi", SearchOption.AllDirectories);
                mpgFiles = di.GetFiles("*.mpg", SearchOption.AllDirectories);
                flvFiles = di.GetFiles("*.flv", SearchOption.AllDirectories);
                wmvFiles = di.GetFiles("*.wmv", SearchOption.AllDirectories);
                foreach (FileInfo fi in mp4Files)
                {
                    listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                }
                foreach (FileInfo fi in aviFiles)
                {
                    listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                }
                foreach (FileInfo fi in mpgFiles)
                {
                    listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                }
                foreach (FileInfo fi in flvFiles)
                {
                    listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                }
                foreach (FileInfo fi in wmvFiles)
                {
                    listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                }

                gridView.DataSource = listMp3Infos;
                _lblCount.Text = gridView.RowCount.ToString() + " files";
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                filePath = _temp;
                txtFilePath.Text = filePath;
            }
        }

        private void CleanFileNames()
        {
            string result = string.Empty;
            try
            {
                filePath = txtFilePath.Text;
                DirectoryInfo di = new DirectoryInfo(filePath);
                mp3Files = di.GetFiles("*.mp3");
                wmaFiles = di.GetFiles("*.wma");
                foreach (FileInfo file in mp3Files)
                {
                    if (file.Name.Contains("%20"))
                    {
                        file.MoveTo(filePath + file.Name.Replace("%20", " "));
                        result += file.Name + Environment.NewLine;
                    }
                }
                foreach (FileInfo file in wmaFiles)
                {
                    if (file.Name.Contains("%20"))
                    {
                        file.MoveTo(filePath + file.Name.Replace("%20", " "));
                        result += file.Name + Environment.NewLine;
                    }
                }
                if (result == string.Empty)
                {
                    lblResult.Text = "No need to clean";
                }
                else
                {
                    ListFiles();
                    lblResult.Text = "Cleaned";
                    MessageBox.Show(result);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void ShowTags(string _path)
        {
            try
            {
                if (!isFolder() && !isVideo())
                {
                    TagLib.File mp3 = TagLib.File.Create(_path);
                    txtArtist.Text = Manipulator.ArrayToString(mp3.Tag.Performers, ",");
                    txtAlbum.Text = mp3.Tag.Album;
                    txtTitle.Text = mp3.Tag.Title;
                    txtTrack.Text = mp3.Tag.Track.ToString();
                    txtYear.Text = mp3.Tag.Year.ToString();
                    txtGenre.Text = Manipulator.ArrayToString(mp3.Tag.Genres, ",");
                    txtLyrics.Text = mp3.Tag.Lyrics;
                    txtComments.Text = mp3.Tag.Comment;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void ShowMultiTags(List<string> fileNames)
        {
            string temp = string.Empty;
            string artistTag = string.Empty;
            string titleTag = string.Empty;
            string albumTag = string.Empty;
            string trackTag = string.Empty;
            string yearTag = string.Empty;
            string genreTag = string.Empty;
            string lyricTag = string.Empty;
            string commentTag = string.Empty;

            TagLib.File tempFile = null;
            try
            {
                tempFile = TagLib.File.Create(fileNames[0]);
                artistTag = Manipulator.ArrayToString(tempFile.Tag.Performers, ",");
                titleTag = tempFile.Tag.Title;
                albumTag = tempFile.Tag.Album;
                trackTag = tempFile.Tag.Track.ToString();
                yearTag = tempFile.Tag.Year.ToString();
                genreTag = Manipulator.ArrayToString(tempFile.Tag.Genres, ",");
                lyricTag = tempFile.Tag.Lyrics;
                commentTag = tempFile.Tag.Comment;
            }
            catch (Exception) { }

            foreach (string filePath in fileNames)
            {
                try
                {
                    TagLib.File tag = TagLib.File.Create(filePath);
                    temp = Manipulator.ArrayToString(tag.Tag.Performers, ",");
                    if (temp != artistTag)
                    {
                        txtArtist.Text = "(multiple values)";
                    }
                    else
                    {
                        txtArtist.Text = temp;
                    }
                    temp = tag.Tag.Album;
                    if (temp != albumTag)
                    {
                        txtAlbum.Text = "(multiple values)";
                    }
                    else
                    {
                        txtAlbum.Text = temp;
                    }
                    temp = tag.Tag.Title;
                    if (temp != titleTag)
                    {
                        txtTitle.Text = "(multiple values)";
                    }
                    else
                    {
                        txtTitle.Text = temp;
                    }
                    temp = tag.Tag.Track.ToString();
                    if (temp != trackTag)
                    {
                        txtTrack.Text = "(multiple values)";
                    }
                    else
                    {
                        txtTrack.Text = temp;
                    }
                    temp = tag.Tag.Year.ToString();
                    if (temp != yearTag)
                    {
                        txtYear.Text = "(multiple values)";
                    }
                    else
                    {
                        txtYear.Text = temp;
                    }
                    temp = Manipulator.ArrayToString(tag.Tag.Genres, ",");
                    if (temp != genreTag)
                    {
                        txtGenre.Text = "(multiple values)";
                    }
                    else
                    {
                        txtGenre.Text = temp;
                    }
                    temp = tag.Tag.Lyrics;
                    if (temp != lyricTag)
                    {
                        txtLyrics.Text = "(multiple values)";
                    }
                    else
                    {
                        txtLyrics.Text = temp;
                    }
                    temp = tag.Tag.Comment;
                    if (temp != commentTag)
                    {
                        txtComments.Text = "(multiple values)";
                    }
                    else
                    {
                        txtComments.Text = temp;
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }

        private void _btnSave_Click(object sender, EventArgs e)
        {
            if (gridView.SelectedRows.Count == 1)
            {
                try
                {
                    TagLib.File mp3 = TagLib.File.Create(selectedFileName);
                    mp3.Tag.Performers = new string[] { txtArtist.Text };
                    mp3.Tag.Album = txtAlbum.Text;
                    mp3.Tag.Title = txtTitle.Text;
                    mp3.Tag.Track = Convert.ToUInt32(txtTrack.Text);
                    mp3.Tag.Year = Convert.ToUInt32(txtYear.Text);
                    mp3.Tag.Genres = new string[] { txtGenre.Text };
                    mp3.Tag.Lyrics = txtLyrics.Text;
                    mp3.Tag.Comment = txtComments.Text;
                    mp3.Save();
                    lblResult.Text = "Saved";
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                foreach (string filePath in ls)
                {
                    TagLib.File mp3 = TagLib.File.Create(filePath);
                    if (txtArtist.Text != "(multiple values)")
                    {
                        mp3.Tag.Performers = new string[] { txtArtist.Text };
                    }
                    if (txtAlbum.Text != "(multiple values)")
                    {
                        mp3.Tag.Album = txtAlbum.Text;
                    }
                    if (txtTitle.Text != "(multiple values)")
                    {
                        mp3.Tag.Title = txtTitle.Text;
                    }
                    if (txtTrack.Text != "(multiple values)")
                    {
                        mp3.Tag.Track = Convert.ToUInt32(txtTrack.Text);
                    }
                    if (txtYear.Text != "(multiple values)")
                    {
                        mp3.Tag.Year = Convert.ToUInt32(txtYear.Text);
                    }
                    if (txtGenre.Text != "(multiple values)")
                    {
                        mp3.Tag.Genres = new string[] { txtGenre.Text };
                    }
                    if (txtLyrics.Text != "(multiple values)")
                    {
                        mp3.Tag.Lyrics = txtLyrics.Text;
                    }
                    if (txtComments.Text != "(multiple values)")
                    {
                        mp3.Tag.Comment = txtComments.Text;
                    }
                    mp3.Save();
                    lblResult.Text = "Saved";
                }
            }
        }

        private void gridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            lblResult.Text = gridView.SelectedRows.Count.ToString() + " selected";
            if (gridView.SelectedRows.Count == 1)
            {
                selectedRowIndex = gridView.CurrentRow.Index;
                DisplaySelectedFileInfo();
            }
            else
            {
                DisplayMultiSelectedFilesInfo();
            }
        }

        private void DisplaySelectedFileInfo()
        {
            try
            {
                if (gridView.CurrentRow.Index != selectedRowIndex || gridView.CurrentRow.Index == 0)
                {
                    selectedFileName = gridView.CurrentRow.Cells["ColumnPath"].Value.ToString();
                    ShowTags(selectedFileName);
                    lblResult.Text = "";
                }
                else { }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void DisplayMultiSelectedFilesInfo()
        {
            string selectedPath = gridView.CurrentRow.Cells["ColumnPath"].Value.ToString();
            if (isFolder() || isVideo())
            {
                //
            }
            else
            {
                ls.Clear();
                foreach (DataGridViewRow row in gridView.SelectedRows)
                {
                    ls.Add(row.Cells["ColumnPath"].Value.ToString());
                }
                ShowMultiTags(ls);
            }
        }

        private void gridView_SelectionChanged(object sender, EventArgs e)
        {
            DisplaySelectedFileInfo();
        }

        //http://forum.codecall.net/csharp-tutorials/20420-tutorial-playing-mp3-files-c.html#post199646
        //http://www.codeproject.com/Articles/14709/Playing-MP3s-using-MCI
        private void PlaySelectedMp3Files()
        {
            try
            {
                selectedFileName = gridView.CurrentRow.Cells["ColumnPath"].Value.ToString();
                if (selectedFileName.EndsWith("mp4") || selectedFileName.EndsWith("mpg") ||
                    selectedFileName.EndsWith("flv") || selectedFileName.EndsWith("wmv") ||
                    selectedFileName.EndsWith("avi") || selectedFileName.EndsWith("flac") && _btnList.Enabled == false)
                {
                    System.Diagnostics.Process.Start(selectedFileName);
                }
                else
                {
                    //mciSendString("open \"" + selectedFileName + "\" type mpegvideo alias MediaFile", null, 0, IntPtr.Zero);
                    //mciSendString("play MediaFile" + playMode, null, 0, IntPtr.Zero);

                    if (windowsMediaPlayer.playState == WMPLib.WMPPlayState.wmppsPlaying)
                    {
                        if (_chkReplay.Checked == true) // loop
                        {
                            windowsMediaPlayer.settings.setMode("loop", true);
                        }
                        else if (_chkShuffle.Checked == true)
                        {
                            windowsMediaPlayer.settings.setMode("shuffle", true);
                        }
                        else
                        {
                            windowsMediaPlayer.settings.setMode("loop", false);
                            windowsMediaPlayer.settings.setMode("shuffle", false);
                        }
                    }

                    else
                    {
                        string myPlaylist = "MyPlayList";

                        plItems = windowsMediaPlayer.playlistCollection.getByName(myPlaylist);

                        pl = windowsMediaPlayer.playlistCollection.newPlaylist(myPlaylist);

                        int index = getSongIndex(selectedFileName);

                        string fi = string.Empty;
                        if (_chkPlayAll.Checked == true) // play all songs in list
                        {
                            for (int i = index; i <= gridView.Rows.Count - 1; i++)
                            {
                                fi = gridView.Rows[i].Cells["ColumnPath"].Value.ToString();
                                if (fi.EndsWith("mp3") || fi.EndsWith("wma") || fi.EndsWith("flac"))
                                {
                                    WMPLib.IWMPMedia m1 = windowsMediaPlayer.newMedia(fi);
                                    pl.appendItem(m1);
                                }
                            }
                        }
                        else // play selected songs
                        {
                            foreach (DataGridViewRow row in gridView.SelectedRows)
                            {
                                fi = row.Cells["ColumnPath"].Value.ToString();
                                if (fi.EndsWith("mp3") || fi.EndsWith("wma") || fi.EndsWith("flac"))
                                {
                                    WMPLib.IWMPMedia m1 = windowsMediaPlayer.newMedia(fi);
                                    pl.appendItem(m1);
                                }
                            }
                        }

                        if (_chkReplay.Checked == true)
                        {
                            windowsMediaPlayer.settings.setMode("loop", true);
                        }

                        if (_chkShuffle.Checked == true)
                        {
                            windowsMediaPlayer.settings.setMode("shuffle", true);
                        }

                        windowsMediaPlayer.currentPlaylist = pl;
                        windowsMediaPlayer.controls.play();
                        _btnPlayAll.Text = "Pause";

                        timerNowPlayingText.Enabled = true;

                        this.Text = "Now Playing - " + Path.GetFileNameWithoutExtension(selectedFileName) + " | ";
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void _btnOpenFolder_Click(object sender, EventArgs e)
        {
            try
            {
                selectedFileName = gridView.CurrentRow.Cells["ColumnPath"].Value.ToString();
                if (isFolder())
                {
                    Process.Start(selectedFileName);
                }
                else
                {
                    Process.Start("explorer.exe", @"/select, " + selectedFileName);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("No song in list", "Warning");
                txtFilePath.Text = filePath;
            }
        }

        private void _btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                if (!isFolder())
                {
                    //mciSendString("close MediaFile", null, 0, IntPtr.Zero);
                    _btnPlayAll.Text = "Play";
                }

                windowsMediaPlayer.controls.stop();
                windowsMediaPlayer.close();

                this.Text = "Mp3TagReader";

                timerNowPlayingText.Enabled = false;
                _chkPlayAll.Enabled = true;
            }
            catch
            {
                MessageBox.Show("No song in list", "Warning");
                return;
            }
        }

        private void _btnList_Click(object sender, EventArgs e)
        {
            ListFiles();
        }

        private void _btnSearch_Click(object sender, EventArgs e)
        {
            if (_btnList.Enabled == true)
            {
                _btnList.Enabled = false;
                _btnUntagged.Enabled = true;
                _btnSearch.Text = "Search ON";
                txtFilePath.Focus();
                txtFilePath.Clear();
            }
            else
            {
                _btnList.Enabled = true;
                _btnUntagged.Enabled = true;
                _btnSearch.Text = "Search OFF";
                txtFilePath.Focus();
            }
        }

        private void loopThroughFolders(DirectoryInfo folder, string searchString)
        {
            DirectoryInfo[] folders = folder.GetDirectories();

            if (folders.Length > 0)
            {
                foreach (DirectoryInfo folderTemp in folders)
                {
                    if (folderTemp.Name.ToLower().Contains(searchString.ToLower()))
                    {
                        listMp3Infos.Add(new FolderInfo(folderTemp.FullName, folderTemp.Name));
                    }

                    else
                    {
                        loopThroughFolders(folderTemp, searchString);
                    }
                }
            }
        }

        private DirectoryInfo[] folders = null;
        private DirectoryInfo[] folders2 = null;

        private void txtFilePath_TextChanged(object sender, EventArgs e)
        {
            if (_btnList.Enabled == false)
            {
                string searchString = txtFilePath.Text;
                ClearMp3List();
                DirectoryInfo di_File;
                DirectoryInfo di2_File;

                DirectoryInfo di_Folder;
                DirectoryInfo di2_Folder;

                // loop through all MP3 ONCE
                int count = 0;
                try
                {
                    count = mp3Files.Length;
                }
                catch
                {
                    count = 0;
                }
                if (txtFilePath.Text.Length == 0 && count < 2000)
                {
                    di_File = new DirectoryInfo(@"E:\Music");
                    mp3Files = di_File.GetFiles("*.mp3", SearchOption.AllDirectories);
                    wmaFiles = di_File.GetFiles("*.wma", SearchOption.AllDirectories);
                    flacFiles = di_File.GetFiles("*.flac", SearchOption.AllDirectories);

                    di2_File = new DirectoryInfo(@"E:\Untagged Music");
                    mp3Files_Untagged = di2_File.GetFiles("*.mp3", SearchOption.AllDirectories);
                    wmaFiles_Untagged = di2_File.GetFiles("*.wma", SearchOption.AllDirectories);
                    flacFiles_Untagged = di2_File.GetFiles("*.flac", SearchOption.AllDirectories);

                    // loop through folders
                    di_Folder = new DirectoryInfo(@"E:\Music");
                    di2_Folder = new DirectoryInfo(@"E:\Videos");
                    folders = di_Folder.GetDirectories();
                    folders2 = di2_Folder.GetDirectories();
                }

                // folder search result
                foreach (DirectoryInfo folder in folders)
                {
                    if (folder.Name.ToLower().Contains(searchString.ToLower()))
                    {
                        listMp3Infos.Add(new FolderInfo(folder.FullName, folder.Name));
                    }

                    // continue to search children folders
                    else
                    {
                        loopThroughFolders(folder, searchString);
                    }
                }
                foreach (DirectoryInfo folder in folders2)
                {
                    if (folder.Name.ToLower().Contains(searchString.ToLower()))
                    {
                        listMp3Infos.Add(new FolderInfo(folder.FullName, folder.Name));
                    }

                    // continue to search children folders
                    else
                    {
                        loopThroughFolders(folder, searchString);
                    }
                }

                // music search result
                foreach (FileInfo fi in mp3Files)
                {
                    if (fi.Name.ToLower().Contains(searchString.ToLower()))
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                }
                foreach (FileInfo fi in wmaFiles)
                {
                    if (fi.Name.ToLower().Contains(searchString.ToLower()))
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                }
                foreach (FileInfo fi in flacFiles)
                {
                    if (fi.Name.ToLower().Contains(searchString.ToLower()))
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                }

                // search in Untagged Folder
                foreach (FileInfo fi in mp3Files_Untagged)
                {
                    if (fi.Name.ToLower().Contains(searchString.ToLower()))
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                }
                foreach (FileInfo fi in wmaFiles_Untagged)
                {
                    if (fi.Name.ToLower().Contains(searchString.ToLower()))
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                }
                foreach (FileInfo fi in flacFiles_Untagged)
                {
                    if (fi.Name.ToLower().Contains(searchString.ToLower()))
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                }

                // video search result
                di_File = new DirectoryInfo(@"E:\Videos");
                mp4Files = di_File.GetFiles("*.mp4", SearchOption.AllDirectories);
                aviFiles = di_File.GetFiles("*.avi", SearchOption.AllDirectories);
                mpgFiles = di_File.GetFiles("*.mpg", SearchOption.AllDirectories);
                flvFiles = di_File.GetFiles("*.flv", SearchOption.AllDirectories);
                wmvFiles = di_File.GetFiles("*.wmv", SearchOption.AllDirectories);
                foreach (FileInfo fi in mp4Files)
                {
                    if (fi.Name.ToLower().Contains(searchString.ToLower()) && searchString.ToLower() != @"E:\Videos" || searchString.ToLower() == string.Empty)
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                }
                foreach (FileInfo fi in aviFiles)
                {
                    if (fi.Name.ToLower().Contains(searchString.ToLower()) && searchString.ToLower() != @"E:\Videos" || searchString.ToLower() == string.Empty)
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                }
                foreach (FileInfo fi in mpgFiles)
                {
                    if (fi.Name.ToLower().Contains(searchString.ToLower()) && searchString.ToLower() != @"E:\Videos" || searchString.ToLower() == string.Empty)
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                }
                foreach (FileInfo fi in flvFiles)
                {
                    if (fi.Name.ToLower().Contains(searchString.ToLower()) && searchString.ToLower() != @"E:\Videos" || searchString.ToLower() == string.Empty)
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                }
                foreach (FileInfo fi in wmvFiles)
                {
                    if (fi.Name.ToLower().Contains(searchString.ToLower()) && searchString.ToLower() != @"E:\Videos" || searchString.ToLower() == string.Empty)
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                }

                // check to prevent null exception
                if (listMp3Infos.Count > 0)
                {
                    gridView.DataSource = listMp3Infos;
                    _lblCount.Text = gridView.RowCount.ToString() + " results";
                }
            }
        }

        private void txtLyrics_DoubleClick(object sender, EventArgs e)
        {
            if (txtLyrics.Text != string.Empty)
            {
                LyricsViewer lv = new LyricsViewer(txtArtist.Text, txtTitle.Text, txtLyrics.Text);
                lv.Show();
            }
        }

        private void chkReplay_CheckedChanged(object sender, EventArgs e)
        {
            if (windowsMediaPlayer.playState == WMPLib.WMPPlayState.wmppsPlaying)
            {
                if (_chkReplay.Checked == true) // loop
                {
                    windowsMediaPlayer.settings.setMode("loop", true);
                }
                else
                {
                    windowsMediaPlayer.settings.setMode("loop", false);
                }
            }
        }

        private void _btnUntagged_Click(object sender, EventArgs e)
        {
            TagLib.File audio;
            ClearMp3List();
            try
            {
                foreach (FileInfo fi in mp3Files)
                {
                    audio = TagLib.File.Create(fi.FullName, ReadStyle.None);
                    if (audio.Tag.Album != null)
                    {
                        if (audio.Tag.Album.ToLower().Contains("zing") || audio.Tag.Album.ToLower().Contains(".com") || audio.Tag.Album.ToLower().Contains(".vn") || audio.Tag.Album.ToLower().Contains(".org"))
                        {
                            listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                        }
                    }
                    if (audio.Tag.Album == null || Manipulator.ArrayToString(audio.Tag.Performers, ",") == string.Empty || Manipulator.ArrayToString(audio.Tag.Artists, ",") == string.Empty || audio.Tag.Title == string.Empty)
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                }
                foreach (FileInfo fi in wmaFiles)
                {
                    audio = TagLib.File.Create(fi.FullName, ReadStyle.None);
                    if (audio.Tag.Album != null)
                    {
                        if (audio.Tag.Album.ToLower().Contains("zing"))
                        {
                            listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                        }
                    }
                    if (audio.Tag.Album == null || Manipulator.ArrayToString(audio.Tag.Performers, ",") == string.Empty || Manipulator.ArrayToString(audio.Tag.Artists, ",") == string.Empty || audio.Tag.Title == string.Empty)
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                }
                gridView.DataSource = listMp3Infos;
                _lblCount.Text = gridView.RowCount.ToString() + " files";
            }
            catch (CorruptFileException ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("No song in list", "Warning");
                return;
            }
        }

        private void _btnSwitch_Click(object sender, EventArgs e)
        {
            if (txtFilePath.Text == @"E:\Untagged Music")
            {
                txtFilePath.Text = @"E:\Music";
            }
            else
            {
                txtFilePath.Text = @"E:\Untagged Music";
            }
        }

        private void _btnPlayList_Click(object sender, EventArgs e)
        {
            if (listMp3Infos.Count == 0)
            {
                MessageBox.Show("No song in list", "Warning");
                return;
            }

            if (_btnPlayAll.Text == "Play")
            {
                PlaySelectedMp3Files();
                _chkPlayAll.Enabled = false;
            }

            else if (_btnPlayAll.Text == "Pause")
            {
                windowsMediaPlayer.controls.pause();
                _btnPlayAll.Text = "Resume";
                timerNowPlayingText.Enabled = false;
            }

            else if (_btnPlayAll.Text == "Resume")
            {
                windowsMediaPlayer.controls.play();
                _btnPlayAll.Text = "Pause";
                timerNowPlayingText.Enabled = true;
            }
        }

        private void gridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            // open folder
            try
            {
                selectedFileName = gridView.CurrentRow.Cells["ColumnPath"].Value.ToString();
                if (isFolder())
                {
                    ClearMp3List();
                    string searchString = txtFilePath.Text;
                    DirectoryInfo di = new DirectoryInfo(selectedFileName);
                    DirectoryInfo[] folders = di.GetDirectories();
                    mp3Files = di.GetFiles("*.mp3", SearchOption.TopDirectoryOnly);
                    wmaFiles = di.GetFiles("*.wma", SearchOption.TopDirectoryOnly);
                    mp4Files = di.GetFiles("*.mp4", SearchOption.TopDirectoryOnly);
                    aviFiles = di.GetFiles("*.avi", SearchOption.TopDirectoryOnly);
                    mpgFiles = di.GetFiles("*.mpg", SearchOption.TopDirectoryOnly);
                    flvFiles = di.GetFiles("*.flv", SearchOption.TopDirectoryOnly);
                    wmvFiles = di.GetFiles("*.wmv", SearchOption.TopDirectoryOnly);
                    foreach (DirectoryInfo folder in folders)
                    {
                        listMp3Infos.Add(new FolderInfo(folder.FullName, folder.Name));
                    }
                    foreach (FileInfo fi in mp3Files)
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                    foreach (FileInfo fi in wmaFiles)
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                    foreach (FileInfo fi in mp4Files)
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                    foreach (FileInfo fi in aviFiles)
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                    foreach (FileInfo fi in mpgFiles)
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                    foreach (FileInfo fi in flvFiles)
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                    foreach (FileInfo fi in wmvFiles)
                    {
                        listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                    }
                    gridView.DataSource = listMp3Infos;
                    _lblCount.Text = gridView.RowCount.ToString() + " results";
                }
                else // play with KMP
                {
                    selectedFileName = gridView.CurrentRow.Cells["ColumnPath"].Value.ToString();
                    System.Diagnostics.Process.Start(selectedFileName);
                }
            }
            catch (Exception) { }
        }

        private bool isFolder()
        {
            string selectedPath = gridView.CurrentRow.Cells["ColumnPath"].Value.ToString();
            if (!selectedPath.EndsWith("mp3") && !selectedPath.EndsWith("wma")
                && !selectedPath.EndsWith("mp4") && !selectedPath.EndsWith("avi")
                && !selectedPath.EndsWith("flv") && !selectedPath.EndsWith("wmv")
                && !selectedPath.EndsWith("mpg") && !selectedPath.EndsWith("flac"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private bool isVideo()
        {
            string selectedPath = gridView.CurrentRow.Cells["ColumnPath"].Value.ToString();
            if (selectedPath.EndsWith("mp4") || selectedPath.EndsWith("avi")
                || selectedPath.EndsWith("flv") || selectedPath.EndsWith("wmv")
                || selectedPath.EndsWith("mpg") || selectedPath.EndsWith("flac"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private string folderOf(string filePath) // return folder of the selected file
        {
            selectedFileName = gridView.CurrentRow.Cells["ColumnPath"].Value.ToString();
            return Path.GetDirectoryName(selectedFileName);
        }

        private void lblAlbum_Click(object sender, EventArgs e)
        {
            if (txtAlbum.Text == string.Empty || txtAlbum.Text.Contains("zing") || txtAlbum.Text.Contains("."))
            {
                txtAlbum.Text = "Unknown";
            }
        }

        private string fileNameOf()
        {
            string fileName = string.Empty;
            fileName = Path.GetFileName(selectedFileName);
            return fileName;
        }

        private string getArtistFromFileName(string fileName)
        {
            string artistName = string.Empty;
            int index = 0;
            index = fileName.LastIndexOf(".");
            if (index > 0)
            {
                artistName = fileName.Substring(0, index);
            }
            index = artistName.LastIndexOf("-");
            if (index > 0)
            {
                artistName = artistName.Substring(index + 1).Trim();
            }
            return artistName;
        }

        private string getTitleFromFileName(string fileName)
        {
            string title = string.Empty;
            int index = 0;
            index = fileName.LastIndexOf(".");
            if (index > 0)
            {
                title = fileName.Substring(0, index);
            }
            index = title.LastIndexOf("-");
            if (index > 0)
            {
                title = title.Substring(0, index).Trim();
            }
            return title;
        }

        private void lblComments_Click(object sender, EventArgs e)
        {
            txtComments.Text = string.Empty;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void fix20ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CleanFileNames();
        }

        private void lblArtist_Click(object sender, EventArgs e)
        {
            if (flag == 0)
            {
                string artistName = string.Empty;
                string fileName = fileNameOf();
                artistName = getArtistFromFileName(fileName);
                txtArtist.Text = artistName;
                flag = 1;
            }
            else
            {
                string artistName = string.Empty;
                string fileName = fileNameOf();
                artistName = getTitleFromFileName(fileName);
                txtArtist.Text = artistName;
                flag = 0;
            }
        }

        private void lblTitle_Click(object sender, EventArgs e)
        {
            if (flag == 0)
            {
                string title = string.Empty;
                string fileName = fileNameOf();
                title = getTitleFromFileName(fileName);
                txtTitle.Text = title;
                flag = 1;
            }
            else
            {
                string title = string.Empty;
                string fileName = fileNameOf();
                title = getArtistFromFileName(fileName);
                txtTitle.Text = title;
                flag = 0;
            }
        }

        // http://samuelhaddad.com/2009/03/22/c-net-and-lyricwiki-to-lookup-lyrics/
        private void _btnGetLyrics_Click(object sender, EventArgs e)
        {
            LyricWiki wiki = new LyricWiki();
            LyricsResult result = new LyricsResult();
            string artist = txtArtist.Text;
            string title = txtTitle.Text;
            if (wiki.checkSongExists(artist, title))
            {
                result = wiki.getSong(artist, title);
                Process.Start(result.url);

                //Encoding iso8859 = Encoding.GetEncoding("ISO-8859-1");
                //txtLyrics.Text = Encoding.UTF8.GetString(iso8859.GetBytes(result.lyrics));
            }
            else
            {
                MessageBox.Show("Lyrics not found");

                Searcher searchLyric = new Searcher(title + " " + artist);
                searchLyric.Show();
            }
        }

        private void _btnAllVids_Click(object sender, EventArgs e)
        {
            ClearMp3List();
            DirectoryInfo di = new DirectoryInfo(@"E:\Videos");
            string searchString = string.Empty;
            mp4Files = di.GetFiles("*.mp4", SearchOption.AllDirectories);
            aviFiles = di.GetFiles("*.avi", SearchOption.AllDirectories);
            mpgFiles = di.GetFiles("*.mpg", SearchOption.AllDirectories);
            flvFiles = di.GetFiles("*.flv", SearchOption.AllDirectories);
            wmvFiles = di.GetFiles("*.wmv", SearchOption.AllDirectories);
            foreach (FileInfo fi in mp4Files)
            {
                if (fi.Name.ToLower().Contains(searchString.ToLower()) && searchString.ToLower() != @"E:\Videos" || searchString.ToLower() == string.Empty)
                {
                    listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                }
            }
            foreach (FileInfo fi in aviFiles)
            {
                if (fi.Name.ToLower().Contains(searchString.ToLower()) && searchString.ToLower() != @"E:\Videos" || searchString.ToLower() == string.Empty)
                {
                    listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                }
            }
            foreach (FileInfo fi in mpgFiles)
            {
                if (fi.Name.ToLower().Contains(searchString.ToLower()) && searchString.ToLower() != @"E:\Videos" || searchString.ToLower() == string.Empty)
                {
                    listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                }
            }
            foreach (FileInfo fi in flvFiles)
            {
                if (fi.Name.ToLower().Contains(searchString.ToLower()) && searchString.ToLower() != @"E:\Videos" || searchString.ToLower() == string.Empty)
                {
                    listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                }
            }
            foreach (FileInfo fi in wmvFiles)
            {
                if (fi.Name.ToLower().Contains(searchString.ToLower()) && searchString.ToLower() != @"E:\Videos" || searchString.ToLower() == string.Empty)
                {
                    listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                }
            }
            gridView.DataSource = listMp3Infos;
            _lblCount.Text = gridView.RowCount.ToString() + " results";
        }

        private void _btnInfo_Click(object sender, EventArgs e)
        {
            FullInfo info = new FullInfo(selectedFileName);
            info.Show();
        }

        private void timerSong_Tick(object sender, EventArgs e)
        {
            try
            {
                if (windowsMediaPlayer.playState == WMPLib.WMPPlayState.wmppsStopped)
                {
                    _btnStop_Click(null, null);
                }

                else
                {
                    if (_btnPlayAll.Text == "Pause")
                    {
                        int songIndex = 0;
                        string currentSong = windowsMediaPlayer.controls.currentItem.sourceURL;
                        if (currentSong != selectedFileName) // next song
                        {
                            selectedFileName = currentSong;

                            songIndex = getSongIndex(currentSong);

                            gridView.CurrentRow.Selected = false;
                            gridView.Rows[songIndex - 1].Selected = false;
                            gridView.Rows[songIndex].Selected = true;

                            ShowTags(selectedFileName);

                            this.Text = "Now Playing - " + Path.GetFileNameWithoutExtension(currentSong) + " | ";
                        }
                    }
                }

                // notification after copied to clipboard, display "copied" then change back to number of files
                if (_lblCount.Text != "Copied")
                {
                    temp = _lblCount.Text;
                }

                else
                {
                    _lblCount.Text = temp;
                }
            }
            catch { }
        }

        private int getSongIndex(string path)
        {
            int index = 0;
            try
            {
                foreach (DataGridViewRow row in gridView.Rows)
                {
                    if (row.Cells["ColumnPath"].Value.ToString() == path)
                    {
                        index = row.Index;
                    }
                }
            }
            catch
            {
                MessageBox.Show("No song in list", "Warning");
                index = 0;
            }
            return index;
        }

        private void CopyFiles(List<string> ListToCopy)
        {
            if (ListToCopy.Count != 0)
            {
                System.Collections.Specialized.StringCollection FileCollection = new System.Collections.Specialized.StringCollection();

                foreach (string FileToCopy in ListToCopy)
                {
                    FileCollection.Add(FileToCopy);
                }

                if (FileCollection != null)
                {
                    Clipboard.SetFileDropList(FileCollection);
                }
            }
        }

        private void _btnCopy_Click(object sender, EventArgs e)
        {
            if (gridView.SelectedRows.Count == 1)
            {
                selectedFileName = gridView.CurrentRow.Cells["ColumnPath"].Value.ToString();
                ls.Clear();
                ls.Add(selectedFileName);
            }

            if (ls.Count != 0)
            {
                CopyFiles(ls);
                _lblCount.Text = "Copied";
            }
            else
            {
                MessageBox.Show("Nothing to copy", "Warning");
            }
        }

        private void move128KbpsFilesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Please modify the code", "Warning");
            return;

            //string fromFolder = @"E:\Untagged music";
            //string toFolder = @"C:\Users\Lunar\Desktop\BBM";

            //if (fromFolder == string.Empty || toFolder == string.Empty)
            //{
            //    MessageBox.Show("fromFolder is not set", "Warning");
            //    return;
            //}

            //DirectoryInfo di = new DirectoryInfo(fromFolder);
            //mp3Files = di.GetFiles("*.mp3", SearchOption.AllDirectories);
            //wmaFiles = di.GetFiles("*.wma", SearchOption.AllDirectories);
            //TagLib.File audio;
            //try
            //{
            //    foreach (FileInfo fi in mp3Files)
            //    {
            //        audio = TagLib.File.Create(fi.FullName);
            //        if (audio.Properties.AudioBitrate != 128)
            //        {
            //            listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
            //            fi.MoveTo(toFolder + @"\" + fi.Name);
            //        }
            //    }
            //    foreach (FileInfo fi in wmaFiles)
            //    {
            //        audio = TagLib.File.Create(fi.FullName);
            //        if (audio.Properties.AudioBitrate != 128)
            //        {
            //            listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
            //            fi.MoveTo(toFolder + @"\" + fi.Name);
            //        }
            //    }
            //    gridView.DataSource = listMp3Infos;
            //    _lblCount.Text = gridView.RowCount.ToString() + " files";
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.ToString());
            //    return;
            //}
        }

        private void browseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                this.txtFilePath.Text = folderBrowserDialog.SelectedPath;
                filePath = txtFilePath.Text;
            }
            else { }
        }

        private void timerNowPlaying_Tick(object sender, EventArgs e)
        {
            if (this.Text != "Mp3TagReader")
            {
                string sScrollText = this.Text;
                sScrollText = sScrollText.Substring(1,
                    sScrollText.Length - 1) + sScrollText.Substring(0, 1);
                this.Text = sScrollText;
            }
        }

        private void gridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            try
            {
                gridView.Rows[0].Selected = true;
            }
            catch { }
        }

        private void _btnClearLyrics_Click(object sender, EventArgs e)
        {
            try
            {
                txtLyrics.Clear();
            }
            catch { }
        }

        private void browseFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                ClearMp3List();
                listMp3Infos.Add(new Mp3Info(openFileDialog.FileName, openFileDialog.SafeFileName, System.IO.File.GetCreationTime(openFileDialog.FileName)));
                gridView.DataSource = listMp3Infos;
            }
            else { }
        }

        private void deleteFlacFilesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ClearMp3List();

            if (_txtExtensionToRemove.Text.Contains("File"))
            {
                MessageBox.Show("Input file extension first", "Warning");
                _txtExtensionToRemove.Focus();
                return;
            }

            filePath = txtFilePath.Text;
            DirectoryInfo di = new DirectoryInfo(filePath);
            flacFiles = di.GetFiles("*." + _txtExtensionToRemove.Text, SearchOption.AllDirectories);

            foreach (FileInfo fi in flacFiles)
            {
                listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
            }

            gridView.DataSource = listMp3Infos;
            _lblCount.Text = gridView.RowCount.ToString() + " files";

            if (gridView.RowCount == 0)
            {
                MessageBox.Show("Nothing to remove", "Warning");
                return;
            }

            if (MessageBox.Show("Will you really remove " + _lblCount.Text + " items in " + filePath + " ?", "Warning", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                foreach (FileInfo fi in flacFiles)
                {
                    System.IO.File.Delete(fi.FullName);
                }

                MessageBox.Show("Success", "Warning");

                flacFiles = di.GetFiles("*." + _txtExtensionToRemove.Text, SearchOption.AllDirectories);

                foreach (FileInfo fi in flacFiles)
                {
                    listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                }

                gridView.DataSource = listMp3Infos;
                _lblCount.Text = gridView.RowCount.ToString() + " files";
            }
            else { }
        }

        private void _btnPrev_Click(object sender, EventArgs e)
        {
            if (windowsMediaPlayer.playState == WMPLib.WMPPlayState.wmppsStopped)
            {
                MessageBox.Show("Not Playing", "Warning");
                return;
            }

            try
            {
                windowsMediaPlayer.controls.previous();
            }
            catch { }
        }

        private void _btnNext_Click(object sender, EventArgs e)
        {
            if (windowsMediaPlayer.playState == WMPLib.WMPPlayState.wmppsStopped)
            {
                MessageBox.Show("Not Playing", "Warning");
                return;
            }

            try
            {
                windowsMediaPlayer.controls.next();
            }
            catch { }
        }

        private void gridView_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }

            else if (e.Data.GetDataPresent(typeof(ListViewItem)))
            {
                e.Effect = DragDropEffects.Copy;
            }
        }

        private void gridView_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                gridView.DataSource = null;
            }
            catch (Exception) { }

            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            foreach (string file in files)
            {
                listMp3Infos.Add(new Mp3Info(file, System.IO.Path.GetFileName(file), System.IO.File.GetCreationTime(file)));
            }
            gridView.DataSource = listMp3Infos;
            _lblCount.Text = gridView.RowCount.ToString() + " files";
        }

        private void searchZINGToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Searcher zs = new Searcher("");
            zs.Show();
        }

        private void _chkShuffle_CheckedChanged(object sender, EventArgs e)
        {
            if (_chkShuffle.Checked == true)
            {
                windowsMediaPlayer.settings.setMode("shuffle", true);
                _chkPlayAll.Checked = true;
            }
            else
            {
                windowsMediaPlayer.settings.setMode("shuffle", false);
            }
        }

        private TreeNode m_OldSelectNode;

        private void treeViewFolder_MouseUp(object sender, MouseEventArgs e)
        {
            // Show menu only if the right mouse button is clicked.
            if (e.Button == MouseButtons.Right)
            {
                // Point where the mouse is clicked.
                Point p = new Point(e.X, e.Y);

                // Get the node that the user has clicked.
                TreeNode node = treeViewFolder.GetNodeAt(p);
                if (node != null)
                {
                    // Select the node the user has clicked.
                    // The node appears selected until the menu is displayed on the screen.
                    m_OldSelectNode = treeViewFolder.SelectedNode;
                    treeViewFolder.SelectedNode = node;

                    contextMenuFolder.Show(treeViewFolder, p);

                    // Highlight the selected node.
                    treeViewFolder.SelectedNode = m_OldSelectNode;
                }
            }
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                txtFilePath.Text = m_OldSelectNode.FullPath;
                ListFiles();
            }
            catch (Exception) { }
        }

        private void treeViewFolder_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.Nodes[0].Text == "")
            {
                TreeNode node = fe.EnumerateDirectory(e.Node);
            }
        }

        private void openFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Process.Start("explorer.exe", @"/select, " + m_OldSelectNode.FullPath);
            if (Path.HasExtension(m_OldSelectNode.FullPath))
            {
                Process.Start(Path.GetDirectoryName(m_OldSelectNode.FullPath));
            }

            else
            {
                Process.Start(m_OldSelectNode.FullPath);
            }
        }

        private void _btnDisableTimerSong_Click(object sender, EventArgs e)
        {
            if (timerSong.Enabled == true)
            {
                timerSong.Enabled = false;
                _btnDisableTimerSong.Text = "Enable Auto Find Song";
            }

            else if (timerSong.Enabled == false)
            {
                timerSong.Enabled = true;
                _btnDisableTimerSong.Text = "Disable Auto Find Song";
            }
        }

        private void lblTrack_Click(object sender, EventArgs e)
        {
            if (txtTrack.Text == "0" || txtTrack.Text == string.Empty)
            {
                txtTrack.Text = "1";
            }
            else
            {
                txtTrack.Text = (Convert.ToInt32(txtTrack.Text) + 1).ToString();
            }
        }

        private void lblYear_Click(object sender, EventArgs e)
        {
            if (txtYear.Text == "0" || txtYear.Text == string.Empty)
            {
                txtYear.Text = DateTime.Now.Year.ToString();
            }
            else
            {
                txtYear.Text = (Convert.ToInt32(txtYear.Text) - 1).ToString();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            TagLib.File audio;
            ClearMp3List();
            try
            {
                foreach (FileInfo fi in mp3Files)
                {
                    audio = TagLib.File.Create(fi.FullName, ReadStyle.None);
                    if (audio.Tag.Album != null)
                    {
                        if (audio.Tag.Album.ToLower().Contains("/") || Manipulator.ArrayToString(audio.Tag.Performers, ",").ToLower().Contains("/") || Manipulator.ArrayToString(audio.Tag.Artists, ",").ToLower().Contains("/") || audio.Tag.Title.ToLower().Contains("/"))
                        {
                            listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                        }
                    }
                }
                foreach (FileInfo fi in wmaFiles)
                {
                    audio = TagLib.File.Create(fi.FullName, ReadStyle.None);
                    if (audio.Tag.Album != null)
                    {
                        if (audio.Tag.Album.ToLower().Contains("/") || Manipulator.ArrayToString(audio.Tag.Performers, ",").ToLower().Contains("/") || Manipulator.ArrayToString(audio.Tag.Artists, ",").ToLower().Contains("/") || audio.Tag.Title.ToLower().Contains("/"))
                        {
                            listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                        }
                    }
                }
                gridView.DataSource = listMp3Infos;
                _lblCount.Text = gridView.RowCount.ToString() + " files";
            }
            catch (CorruptFileException ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
        }

        private void checkDuplicateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TagLib.File audio;
            ClearMp3List();
            try
            {
                foreach (FileInfo fi in mp3Files)
                {
                    audio = TagLib.File.Create(fi.FullName, ReadStyle.None);
                    if (audio.Tag.Album != null)
                    {
                        if (audio.Tag.Album.ToLower().Contains("/") || Manipulator.ArrayToString(audio.Tag.Performers, ",").ToLower().Contains("/") || Manipulator.ArrayToString(audio.Tag.Artists, ",").ToLower().Contains("/") || audio.Tag.Title.ToLower().Contains("/"))
                        {
                            listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                        }
                    }
                }
                foreach (FileInfo fi in wmaFiles)
                {
                    audio = TagLib.File.Create(fi.FullName, ReadStyle.None);
                    if (audio.Tag.Album != null)
                    {
                        if (audio.Tag.Album.ToLower().Contains("/") || Manipulator.ArrayToString(audio.Tag.Performers, ",").ToLower().Contains("/") || Manipulator.ArrayToString(audio.Tag.Artists, ",").ToLower().Contains("/") || audio.Tag.Title.ToLower().Contains("/"))
                        {
                            listMp3Infos.Add(new Mp3Info(fi.FullName, fi.Name, System.IO.File.GetCreationTime(fi.FullName)));
                        }
                    }
                }
                gridView.DataSource = listMp3Infos;
                _lblCount.Text = gridView.RowCount.ToString() + " files";
            }
            catch (CorruptFileException ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
        }

        private void _btnRemoveFromList_Click(object sender, EventArgs e)
        {
            try
            {
                gridView.Rows.RemoveAt(gridView.CurrentRow.Index);
                gridView.Refresh();
            }
            catch (NullReferenceException ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
        }
    }
}